/**
 * Modbus CRC16 校验工具类
 */
export class CRC16M {
  private uchCRCHi: number = 0xFF;
  private uchCRCLo: number = 0xFF;
  public value: number = 0;

  // CRC16 高位字节预计算表
  private static auchCRCHi: number[] = [
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40
  ];

  // CRC16 低位字节预计算表
  private static auchCRCLo: number[] = [
    0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7,
    0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E,
    0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9,
    0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC,
    0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
    0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32,
    0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D,
    0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38,
    0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF,
    0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
    0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1,
    0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4,
    0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB,
    0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA,
    0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
    0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0,
    0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97,
    0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E,
    0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89,
    0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
    0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83,
    0x41, 0x81, 0x80, 0x40
  ];

  constructor() {
    this.reset();
  }

  /**
   * 更新CRC校验值
   * @param puchMsg 字节数组
   * @param usDataLen 数据长度
   */
  public update(puchMsg: Uint8Array, usDataLen: number): void {
    for (let i = 0; i < usDataLen; i++) {
      const uIndex = (this.uchCRCHi ^ puchMsg[i]) & 0xFF;
      this.uchCRCHi = this.uchCRCLo ^ CRC16M.auchCRCHi[uIndex];
      this.uchCRCLo = CRC16M.auchCRCLo[uIndex];
    }
    this.value = ((this.uchCRCHi << 8) | (this.uchCRCLo & 0xFF)) & 0xFFFF;
  }

  /**
   * 重置CRC校验值
   */
  public reset(): void {
    this.value = 0;
    this.uchCRCHi = 0xFF;
    this.uchCRCLo = 0xFF;
  }

  /**
   * 获取当前CRC校验值
   * @returns CRC16校验值
   */
  public getValue(): number {
    return this.value;
  }

  /**
   * 合并两个十六进制字符为一个字节
   * @param src0 第一个字符
   * @param src1 第二个字符
   * @returns 合并后的字节
   */
  private static uniteBytes(src0: number, src1: number): number {
    const _b0 = parseInt(String.fromCharCode(src0), 16);
    const _b1 = parseInt(String.fromCharCode(src1), 16);
    return (_b0 << 4) | _b1;
  }

  /**
   * 十六进制字符串转字节数组
   * @param inHex 十六进制字符串
   * @returns 字节数组
   */
  public static hexToByteArray(inHex: string): Uint8Array {
    let hexlen = inHex.length;
    let result: Uint8Array;

    if (hexlen % 2 === 1) {
      // 奇数长度补零
      hexlen++;
      result = new Uint8Array(Math.ceil(hexlen / 2));
      inHex = '0' + inHex;
    } else {
      result = new Uint8Array(hexlen / 2);
    }

    let j = 0;
    for (let i = 0; i < hexlen; i += 2) {
      result[j] = CRC16M.hexToByte(inHex.substring(i, i + 2));
      j++;
    }
    return result;
  }

  /**
   * 十六进制字符串转字节
   * @param inHex 十六进制字符串
   * @returns 字节
   */
  public static hexToByte(inHex: string): number {
    return parseInt(inHex, 16);
  }

  /**
   * 十六进制字符串转字节数组
   * @param src 十六进制字符串
   * @returns 字节数组
   */
  public static HexString2Buf(src: string): Uint8Array {
    const len = src.length;
    if (len % 2 !== 0) {
      throw new Error("Hex string length must be even");
    }

    const ret = new Uint8Array(len / 2);

    for (let i = 0; i < len; i += 2) {
      const byteStr = src.substring(i, i + 2);
      ret[i / 2] = parseInt(byteStr, 16);
    }

    return ret;
  }

  /**
   * 获取发送缓冲区（自动添加CRC校验）
   * @param toSend 要发送的十六进制字符串
   * @returns 包含CRC校验的字节数组
   */
  public static getSendBuf(toSend: string): Uint8Array {
    const bb = CRC16M.HexString2Buf(toSend);
    const crc16 = new CRC16M();
    crc16.update(bb, bb.length);
    const ri = crc16.getValue();

    // 创建新数组，比原数组长2字节用于存放CRC
    const result = new Uint8Array(bb.length + 2);
    result.set(bb, 0);
    result[bb.length] = (ri >> 8) & 0xFF; // 高字节在前
    result[bb.length + 1] = ri & 0xFF; // 低字节在后

    return result;
  }

  /**
   * 检查缓冲区CRC校验是否有效
   * @param bb 字节数组
   * @returns 校验是否通过
   */
  public static checkBuf(bb: Uint8Array): boolean {
    if (bb.length < 2) {
      return false;
    }

    const crc16 = new CRC16M();
    crc16.update(bb.subarray(0, bb.length - 2), bb.length - 2);
    const ri = crc16.getValue();

    return bb[bb.length - 2] === ((ri >> 8) & 0xFF) &&
      bb[bb.length - 1] === (ri & 0xFF);
  }

  /**
   * 字节数组转十六进制字符串
   * @param raw 字节数组
   * @returns 十六进制字符串
   */
  public static getBufHexStr(raw: Uint8Array): string {
    if (!raw) {
      return '';
    }

    const HEXES = '0123456789ABCDEF';
    let hex = '';

    for (const b of raw) {
      hex += HEXES.charAt((b >> 4) & 0x0F);
      hex += HEXES.charAt(b & 0x0F);
    }

    return hex;
  }

  /**
   * 将 Uint8Array 转换为 ArrayBuffer
   * @param uint8Array 要转换的 Uint8Array
   * @returns 新的 ArrayBuffer
   */
  public static uint8ArrayToArrayBuffer(uint8Array: Uint8Array): ArrayBuffer {
    // 方法1：使用 buffer 属性（共享内存）
    // 注意：这种方式返回的 ArrayBuffer 与原始 Uint8Array 共享内存
    // return uint8Array.buffer;

    // 方法2：创建新的 ArrayBuffer（不共享内存）
    const arrayBuffer = new ArrayBuffer(uint8Array.length);
    new Uint8Array(arrayBuffer).set(uint8Array);
    return arrayBuffer;
  }

  /**
   * 字符串转十六进制字符串
   * @param str 输入字符串
   * @returns 十六进制字符串
   */
  static str2HexStr(str: string): string {
    const chars = '0123456789ABCDEF';
    let sb = '';

    for (let i = 0; i < str.length; i++) {
      const code = str.charCodeAt(i);

      // 处理ASCII字符
      if (code < 0x80) {
        sb += chars.charAt((code >> 4) & 0x0F);
        sb += chars.charAt(code & 0x0F);
      } else {
        // 非ASCII字符转换为UTF-8字节序列
        const bytes = this.stringToBytes(str.substring(i, i + 1));
        for (const byte of bytes) {
          sb += chars.charAt((byte >> 4) & 0x0F);
          sb += chars.charAt(byte & 0x0F);
        }
      }
    }
    return sb;
  }

  /**
   * 字符串转字节数组 (UTF-8)
   * @param str 输入字符串
   * @returns Uint8Array 字节数组
   */
  static stringToBytes(str: string): Uint8Array {
    const bytes = new Uint8Array(str.length * 3); // 预留足够空间
    let pos = 0;

    for (let i = 0; i < str.length; i++) {
      const code = str.charCodeAt(i);

      if (code < 0x80) {
        // 1字节
        bytes[pos++] = code;
      } else if (code < 0x800) {
        // 2字节
        bytes[pos++] = 0xC0 | (code >> 6);
        bytes[pos++] = 0x80 | (code & 0x3F);
      } else if (code >= 0xD800 && code <= 0xDBFF) {
        // 处理4字节UTF-8 (代理对)
        const nextCode = str.charCodeAt(++i);
        if (nextCode >= 0xDC00 && nextCode <= 0xDFFF) {
          const fullCode = ((code - 0xD800) << 10) + (nextCode - 0xDC00) + 0x10000;
          bytes[pos++] = 0xF0 | (fullCode >> 18);
          bytes[pos++] = 0x80 | ((fullCode >> 12) & 0x3F);
          bytes[pos++] = 0x80 | ((fullCode >> 6) & 0x3F);
          bytes[pos++] = 0x80 | (fullCode & 0x3F);
        }
      } else {
        // 3字节
        bytes[pos++] = 0xE0 | (code >> 12);
        bytes[pos++] = 0x80 | ((code >> 6) & 0x3F);
        bytes[pos++] = 0x80 | (code & 0x3F);
      }
    }

    return bytes.subarray(0, pos);
  }

  /**
   * 字节数组转字符串 (UTF-8)
   * @param bytes 字节数组
   * @returns 解码后的字符串
   */
  static bytesToString(bytes: Uint8Array): string {
    let str = '';
    let i = 0;

    while (i < bytes.length) {
      const byte1 = bytes[i++];

      if (byte1 < 0x80) {
        // 1字节
        str += String.fromCharCode(byte1);
      } else if (byte1 >= 0xC0 && byte1 < 0xE0) {
        // 2字节
        const byte2 = bytes[i++];
        str += String.fromCharCode(((byte1 & 0x1F) << 6) | (byte2 & 0x3F));
      } else if (byte1 >= 0xE0 && byte1 < 0xF0) {
        // 3字节
        const byte2 = bytes[i++];
        const byte3 = bytes[i++];
        str += String.fromCharCode(((byte1 & 0x0F) << 12) | ((byte2 & 0x3F) << 6) | (byte3 & 0x3F));
      } else if (byte1 >= 0xF0) {
        // 4字节 (转换为代理对)
        const byte2 = bytes[i++];
        const byte3 = bytes[i++];
        const byte4 = bytes[i++];
        const code = ((byte1 & 0x07) << 18) | ((byte2 & 0x3F) << 12) | ((byte3 & 0x3F) << 6) | (byte4 & 0x3F);

        // 转换为代理对
        str += String.fromCharCode(
          0xD800 + (((code - 0x10000) >> 10) & 0x3FF),
          0xDC00 + ((code - 0x10000) & 0x3FF)
        );
      }
    }

    return str;
  }

  /**
   * 十六进制字符串转二进制字符串
   * @param hexString 十六进制字符串
   * @returns 二进制字符串
   */
  public static hexString2binaryString(hexString: string): string | null {
    if (!hexString || hexString.length % 2 !== 0) {
      return null;
    }

    let bString = '';
    for (let i = 0; i < hexString.length; i++) {
      const tmp = '0000' + parseInt(hexString.substring(i, i + 1), 16).toString(2);
      bString += tmp.substring(tmp.length - 4);
    }
    return bString;
  }

  /**
   * 解码十六进制字符串为十进制字符串
   * @param hexs 十六进制字符串
   * @returns 十进制字符串
   */
  public static decodeHEX(hexs: string): string {
    const numb = parseInt(hexs, 16);
    return numb === 0 ? '' : numb.toString();
  }

  /**
   * 解码十六进制字符串为十进制数
   * @param hexs 十六进制字符串
   * @returns 十进制数
   */
  public static decodeHexInt(hexs: string): number {
    return parseInt(hexs, 16);
  }
}

// 使用示例
const testData = CRC16M.HexString2Buf("010300000002");
const crc16 = new CRC16M();
crc16.update(testData, testData.length);
console.log("CRC16校验值: 0x" + crc16.getValue().toString(16).padStart(4, '0'));

// 构建完整的Modbus RTU帧
const frame = CRC16M.getSendBuf("010300000002");
console.log("完整Modbus帧: " + CRC16M.getBufHexStr(frame));

// 检查帧的CRC校验
const isValid = CRC16M.checkBuf(frame);
console.log("CRC校验结果: " + isValid);